package com.csaba.connector.fhb;

import net.htmlparser.jericho.Source;
import net.htmlparser.jericho.TextExtractor;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.csaba.connector.DummyServer;
import com.csaba.connector.ServiceException;
import com.csaba.connector.fhb.model.FHBCustomer;
import com.csaba.connector.fhb.model.FHBRequestFactory;
import com.csaba.connector.fhb.model.FHBSession;
import com.csaba.connector.model.Session;
import com.csaba.connector.service.AbstractLoginService;

//XXX implement dummy in FHB
//XXX implement ChangePasswordService in FHB
public class FHBLoginService extends AbstractLoginService
{
	//private final static Logger logger = LoggerHelper.getDefaultLogger();

	@Override
	public void execute( final Session nullSession ) throws ServiceException
	{
		if ( customer == null )
			throw new ServiceException("Login service is not correctly initialized.");
		if ( nullSession != null )
			throw new ServiceException("Session is already initialized. Cannot login again in the same session.");

		customer = new FHBCustomer(customer);

		final FHBSession fhb = new FHBSession();
		//proces login
		//		__FORM_NAME__=loginform
		//		%24%24LoginId%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest=...userid...
		//		%24%24UnencodedAuthToken%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest=...password...
		//		%24%24Locale%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest%24%24bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest=HU
		//		scope_object=__LOGIN__
		//		CSRFValidationCode=undefined
		//		ajaxrequest=true
		//		:_CLIENT_TRANSFORMATION__=true

		final NameValuePair[] loginData = fhb.getParamTemplate(5);

		loginData[0] = new BasicNameValuePair("__FORM_NAME__", "loginform");
		loginData[1] = new BasicNameValuePair(
				"$$LoginId$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest",
				customer.getLoginId());//
		loginData[2] = new BasicNameValuePair(
				"$$UnencodedAuthToken$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest",
				customer.getPassword());//
		loginData[3] = new BasicNameValuePair(
				"$$Locale$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest$$bfo_46_channel_46_web_46_function_46_login_58_UnencodedLoginRequest",
				"HU");//FIXME set language
		loginData[4] = new BasicNameValuePair("scope_object", "__LOGIN__");

		final String loginResult = fhb.doPost(
				FHBRequestFactory.getInstance().getAction(FHBRequestFactory.ACTION_LOGIN_PROCESS,
						FHBRequestFactory.TYPE_LOGIN_PROCESS), loginData);
		fhb.debugFile("loginResult", loginResult);
		fhb.checkGenericErrors(loginResult);

		//succesful login - go forward and select the primary user

		//select group
		//		flashenabled=true
		//		time=1317581427306
		//		CSRFValidationCode=ee1f10482c89b8c6b08302930643982
		//		ajaxrequest=true
		//		:__CLIENT_TRANSFORMATION__=true

		final NameValuePair[] sgdata = fhb.getParamTemplate(0);

		final String sgresult = fhb.doPost(
				FHBRequestFactory.getInstance().getAction(FHBRequestFactory.ACTION_SELECT_GROUP,
						FHBRequestFactory.TYPE_SELECT_GROUP), sgdata);
		fhb.debugFile("sgresult", sgresult);
		fhb.checkGenericErrors(sgresult);

		//check if multi-customer
		//		save=
		//		time=1317581427306
		//		CSRFValidationCode=ee1f10482c89b8c6b08302930643982
		//		ajaxrequest=true
		//		:__CLIENT_TRANSFORMATION__=true
		final NameValuePair[] cimcdata = fhb.getParamTemplate(1);
		cimcdata[0] = new BasicNameValuePair("save", "");

		final String cimcresult = fhb.doPost(
				FHBRequestFactory.getInstance().getAction(FHBRequestFactory.ACTION_CHECK_MULTICUSTOMER,
						FHBRequestFactory.TYPE_CHECK_MULTICUSTOMER), cimcdata);
		fhb.debugFile("cimcresult", cimcresult);
		fhb.checkGenericErrors(cimcresult);

		//extract customer name
		if ( !cimcresult.contains(FHBRequestFactory.ACTION_WELCOME) )
		{
			//failed login
			throw new ServiceException("Sorry! Multi-user access is not yet supported.");
		}

		final String content = new TextExtractor(new Source(cimcresult)).toString();
		final int start = content.indexOf(':');
		int stop = content.lastIndexOf(':');
		stop = content.lastIndexOf(' ', stop);
		customer.setName(content.substring(start + 1, stop).trim());

		this.session = fhb;
		DummyServer.getInstance().addSession(session);
	}
}
